# -*- coding: utf-8 -*-

import urllib.request
import os
import re
import threading

def url_open(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent',
                   'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0')
    response = urllib.request.urlopen(url)
    html = response.read()
    return html

def get_page(url):
    html = url_open(url).decode('utf-8')
    p = r'current-comment-page.+(\d\d\d)]'
    page = re.findall(p, html)[0]
    return page


def find_imgs(url):
    html = url_open(url).decode('utf-8')
    p = '<img src="(//.*?jpg)'
    img_address = []
    addresss = list(re.findall(p, html))
    for each in addresss:
        each = 'http:' + each
        img_address.append(each)
    return img_address

def save_imgs(folder, img_address):
    for each in img_address:
        filename = each.split('/')[-1]
        with open(filename, 'wb') as f:
            img = url_open(each)
            f.write(img)

def download(folder='image', page=10):
    os.mkdir(folder)
    os.chdir(folder)

    page = int(input('你要下载多少页图片：'))
    url = 'http://jandan.net/ooxx/'
    page_num = int(get_page(url))
    for i in range(page):
        page_num -= i
        page_url = url + 'page-' + str(page_num) + '#comments'
        img_address = find_imgs(page_url)
        save_imgs(folder, img_address)

if __name__ == '__main__':
    folder = 'image'
    url = 'http://jandan.net/ooxx/'
    t = threading.Thread(target=download, args=(folder, url))  # 多线程抓取
    t.setDaemon(True)  # 声明守护线程
    t.start()  # 开始线程活动
    t.join()  # 阻塞主线程，保证所有子线程都能完全运行结束
    print('over')